package com.example.aoppreventingrepeatsubmissions.controller;


import com.example.aoppreventingrepeatsubmissions.service.SubmissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.lang.reflect.Proxy;

/**
 * @author: hyd
 * @time: 2024.7.9 23:00:00
 */

@RestController
public class SubmissionController {

    @Autowired
    private SubmissionService submissionService;

    private static Jedis jedis = new Jedis("localhost",6379);
    private String lock = "lock";
    private String lockValue = "locked";
    private int gqsj = 5;
    private String ok = "OK";

    @PostMapping("/submit")
    public void handleSubmitForm(@RequestParam String name, @RequestParam int age) {
        SubmissionService submissionServiceProxy = (SubmissionService) Proxy.newProxyInstance(submissionService.getClass().getClassLoader(), new Class[]{SubmissionService.class}, (proxy, method, args) -> {
            SetParams params = new SetParams();
            params.nx().ex(gqsj);
            String res = jedis.set(lock, lockValue,params);
            if (ok.equals(res)){
                Object invoke = method.invoke(submissionService,name,age);
                System.out.println("提交成功");
                return invoke;
            }else {
                System.out.println("不允许重复提交");
                return null;
            }
        });

        submissionServiceProxy.insert(name, age);


//      存疑？第一天晚上return null后汇报一个空指针错误，奇怪的是第二天不报错了

//        try{
//            submissionServiceProxy.insert(name, age);
//        }catch (NullPointerException e){
//            System.out.println("禁止重复提交");
//        }
    }
}


